package com.wnnight.wys.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wnnight.wys.entity.GlobalInfo;
import com.wnnight.wys.entity.config.PropertyStaff;
import com.wnnight.wys.entity.lanlord.Landlord;
import com.wnnight.wys.entity.role.MenuPerm;
import com.wnnight.wys.mapper.config.PropertyStaffMapper;
import com.wnnight.wys.mapper.landlord.LandlordMapper;
import com.wnnight.wys.mapper.role.MenuPermMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class OaUserDetailsService implements UserDetailsService {
    @Autowired
    private PropertyStaffMapper propertyStaffMapper;
    @Autowired
    private LandlordMapper landlordMapper;

    @Autowired
    private MenuPermMapper menuPermMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号去查询用户信息,把用户的权限查出来
        if ("0".equals(GlobalInfo.type)) {
            QueryWrapper<Landlord> wrapper = new QueryWrapper<>();
            wrapper.eq("account",username);
            Landlord landlord = landlordMapper.selectOne(wrapper);
            if (landlord == null){
                throw new UsernameNotFoundException("账号不存在");//抛出异常
            }
            List<MenuPerm> permissions = menuPermMapper.getByRoleId(7);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (MenuPerm permission : permissions) {
                if (permission.getPerms() != null) {
                    authorities.add(new SimpleGrantedAuthority(permission.getPerms()));
                }
            }
            return new OaUser(landlord.getId(),username, landlord.getPassword(), 7,authorities);
        }else {
            PropertyStaff user = propertyStaffMapper.getByAccount(username);
            if (user == null) {
                throw new UsernameNotFoundException("账号不存在");//抛出异常
            }
            List<MenuPerm> permissions = user.getRole().getMenuPerms();
            log.debug("用户信息getPermissions:{}", permissions);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (MenuPerm permission : permissions) {
                if (permission.getPerms() != null) {
                    authorities.add(new SimpleGrantedAuthority(permission.getPerms()));
                }
            }
            return new OaUser(user.getId(), username, user.getPassword(), user.getRole().getId(), authorities);
        }
    }
}
